﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using NHibernate;
using NHibernate.Cfg;


/// <summary>
/// Summary description for NHibernateControl
/// </summary>

public sealed class NHibernateControl
{
    private const string CurrentSessionKey = "nhibernate.current_session";
    private static readonly ISessionFactory sessionFactory;

    static NHibernateControl()
    {
        NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
        cfg.Configure();
        string basePath = System.Web.HttpContext.Current.Server.MapPath(@"../App_Data/Mapping/");
        cfg.AddXmlFile(basePath + "Empleado.hbm.xml");
        cfg.AddXmlFile(basePath + "Factura.hbm.xml");
        cfg.AddXmlFile(basePath + "Gasto.hbm.xml");
        cfg.AddXmlFile(basePath + "Pago.hbm.xml");
        cfg.AddXmlFile(basePath + "Propuesta.hbm.xml");
        cfg.AddXmlFile(basePath + "Usuario.hbm.xml");
        cfg.AddXmlFile(basePath + "PropuestaEmpleado.hbm.xml");
        cfg.AddXmlFile(basePath + "HistoriaPrestamo.hbm.xml");
        sessionFactory = cfg.BuildSessionFactory();
    }

    public static ISession GetCurrentSession()
    {
        HttpContext context = HttpContext.Current;
        ISession currentSession = context.Items[CurrentSessionKey] as ISession;

        if (currentSession == null)
        {
            currentSession = sessionFactory.OpenSession();
            context.Items[CurrentSessionKey] = currentSession;
        }

        return currentSession;
    }

    public static void CloseSession()
    {
        HttpContext context = HttpContext.Current;
        ISession currentSession = context.Items[CurrentSessionKey] as ISession;

        if (currentSession == null)
        {
            // No current session
            return;
        }

        currentSession.Close();
        context.Items.Remove(CurrentSessionKey);
    }

    public static void CloseSessionFactory()
    {
        if (sessionFactory != null)
        {
            sessionFactory.Close();
        }
    }
}